//
//  TableViewOnlineController.m
//  CMS
//
//  Created by Vuong Van Khanh on 10/30/12.
//  Copyright (c) 2012 Rikkei. All rights reserved.
//

#import "TableViewOnlineController.h"
#import "SBJson.h"
#import "StoreVars.h"
#import "Content.h"
#import "ViewChapterOnline.h"
#import "ViewListContentOffline.h"

@implementation TableViewOnlineController
@synthesize tableData;


- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)load 
{
    //do some thing
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
    responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    [self alertStatus:@"Unable to fetch data" :@"Alert"];
//    NSLog(@"Connection error %@", error);
    return;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
//    NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
    respones = [[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding];
    SBJsonParser *jsonParser = [SBJsonParser new];
    
    NSArray *jsonData = (NSArray *) [[jsonParser objectWithString:respones error:nil] objectForKey:@"contents"];
    tableData = [[NSMutableArray alloc] init];
    
    for(NSDictionary *object in jsonData)
    {
        objContent = [[Content alloc] init];
        objContent.contentId = [object objectForKey:@"id"];
        objContent.title = [object objectForKey:@"name"];
        objContent.downloadLink = [object objectForKey:@"download_link"];
        [tableData addObject: objContent]; 
    }
    [[self tableView] reloadData];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"downloadDir: %@", [StoreVars sharedInstance].downloadDir);
   
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    
//    UIButton *localButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [localButton addTarget:self action:@selector(localAction:) forControlEvents:UIControlEventTouchUpInside];
//    [localButton setTitle:@"Local" forState:UIControlStateNormal];
    // create button item -- possible because UIButton subclasses UIView!
//    UIBarButtonItem* localItem = [[UIBarButtonItem alloc] initWithCustomView:localButton];
//    NSArray *arrayButton = [[NSArray alloc] initWithObjects:
//                            localItem, nil];
//    self.navigationItem.leftBarButtonItems = arrayButton;
//    self.navigationItem.leftBarButtonItem = localItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *url = [[NSString alloc] initWithFormat:@"http://192.168.1.24:8888/services/contents?sid=%@&uname=%@", [StoreVars sharedInstance].sessionId, [StoreVars sharedInstance].username];
    NSURL *myURL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(connection)
    {
        //connect
    }
    else{
        //error occur
        [self alertStatus:@"Error when access to server. Please contact to administrator" :@"Error"];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [tableData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    customCells *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[customCells alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    
    Content *rowContent = [tableData objectAtIndex:indexPath.row];
    cell.title.text = rowContent.title;
    cell.lbid.text = rowContent.contentId;
    cell.downloadLink.text = rowContent.downloadLink;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    customCells *selectedCell = (customCells *)[tableView cellForRowAtIndexPath:indexPath];
    ViewChapterOnline *chapterViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle: nil] instantiateViewControllerWithIdentifier:@"ViewChapterOnline"];
    // Navigation logic may go here. Create and push another view controller.
    
//     ViewChapterOnline *chapterViewController = [[ViewChapterOnline alloc] initWithNibName:@"viewDidAppear" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     chapterViewController.contentId = selectedCell.lbid.text;
     [self.navigationController pushViewController:chapterViewController animated:YES];
     
}
- (void) localAction:(id)sender
{
    ViewListContentOffline *viewListContentOffline = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle: nil] instantiateViewControllerWithIdentifier:@"viewListContentOffline"];
    [self.navigationController pushViewController:viewListContentOffline animated:YES];
}

- (IBAction)logoutButtonClicked:(id)sender {
    //call to logout service and pop to root viewController
    [self.navigationController popToRootViewControllerAnimated:YES];
}
   
@end
